﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySite.Enum;
using System.Net;
using System.IO;

namespace MySite.Helper
{
    public class HttpRequestHelper
    {
        #region 生成HttpRequest
        /// <summary>
        /// CreateHttpRequest
        /// </summary>
        /// <param name="url"></param>
        /// <param name="httpMethod"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string CreateHttpRequest(string url, HttpMethod httpMethod, string postData)
        {
            string result = "";

            HttpWebRequest hwq = (HttpWebRequest)HttpWebRequest.Create(url);

            hwq.Method = httpMethod.ToString();

            if (httpMethod == HttpMethod.POST)
            {
                using (StreamWriter sw = new StreamWriter(hwq.GetRequestStream()))
                {
                    sw.Write(postData);
                }
            }

            using (WebResponse response = hwq.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
            }
            return result;
        }
        #endregion

        #region HttpRequestGet
        /// <summary>
        /// HttpRequestGet
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HttpRequestGet(string url)
        {
            return CreateHttpRequest(url, HttpMethod.GET, "");
        }
        #endregion

        #region HttpRequestPOST
        /// <summary>
        /// HttpRequestPOST
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string HttpRequestPOST(string url, string postData)
        {
            return CreateHttpRequest(url, HttpMethod.POST, postData);
        }
        #endregion
    }
}
